// Global constants:
var PLAYGROUND_WIDTH	= 1000 ;
var PLAYGROUND_HEIGHT	= 600;
var REFRESH_RATE		= 15;

// Gloabl animation holder
var playerAnimation = new Array();
var enemies = new Array(); // There are three kind of enemies in the game

// Game state
var gameIsRunning = true;
var playerHit = false;
var timeOfRespawn = 0;
var gameOver = false;
var gameTime = 0;

var playerScore = 0;

var enemySpawn = false;

var isPlayerStaying = false;

// Some helper functions : 

// Function to restart the game:
function restartgame(){
	window.location.reload();
};

function clearGame(){
	$("#playground #sceengraph div").remove ();
	$("#hub table").remove ();

	$.gameQuery.resourceManager.clear();
	gameIsRunning = true;
	playerHit = false;
	timeOfRespawn = 0;
	gameOver = false;
	gameTime = 0;
	playerScore = 0;
	enemySpawn = false;
	isPlayerStaying = false;
	enemies = new Array();
};

// Game objects:
function Player(node){

	this.node = node;
	//this.animations = animations;

	this.grace = false;
	this.replay = 3; 
	this.shield = 3; 
	this.respawnTime = -1;

	// This function damage the ship and return true if this cause the ship to die 
	this.damage = function(){
		if(!this.grace){
			this.shield--;
			if (this.shield == 0){
				return true;
			}
			return false;
		}
		return false;
	};

	// this try to respawn the ship after a death and return true if the game is over
	this.respawn = function(){
		this.replay--;
		if(this.replay==0){
			return true;
		}
		
		this.grace 	= true;
		this.shield	= 3;
		
		this.respawnTime = (new Date()).getTime();
		$(this.node).fadeTo(0, 0.5); 
		return false;
	};

	this.update = function(){
		if((this.respawnTime > 0) && (((new Date()).getTime()-this.respawnTime) > 3000)){
			this.grace = false;
			$(this.node).fadeTo(500, 1); 
			this.respawnTime = -1;
		}
	}

	return true;
}

function Enemy(node){
	this.shield	= 1;
	this.speedx	= -5;
	this.speedy	= 0;
	this.node = $(node);

	// deals with damage endured by an enemy
	this.damage = function(){
		this.shield--;
		if(this.shield == 0){
			return true;
		}
		return false;
	};

	// updates the position of the enemy
	this.update = function(playerNode){
		this.updateX(playerNode);
		this.updateY(playerNode);
	};	
	this.updateX = function(playerNode){
		var newpos = parseInt(this.node.css("left"))+this.speedx;
		this.node.css("left",""+newpos+"px");
	};
	this.updateY= function(playerNode){
		var newpos = parseInt(this.node.css("top"))+this.speedy;
		this.node.css("top",""+newpos+"px");
	};
}

function show_message(title, body, level) {
	var button = '<input type="button" onclick="close_message(' + level + ');" value="Okay!" />';
	
	if(jQuery('#message_box').html() == null) {
		var message = '<div id="message_box"><h1>' + title + '</h1>' + body + '<br/><br/>' + button + '</div>';
		jQuery(document.body).append( message );
		jQuery(document.body).append( '<div id="darkbg"></div>' );
		jQuery('#darkbg').show();
//		jQuery('#darkbg').css('height', jQuery('html, body').height());

		jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
		jQuery('#message_box').show('slow');
	} else {
		var message = '<h1>' + title + '</h1>' + body + '<br/>' + button;
		jQuery('#darkbg').show();
//		jQuery('#darkbg').css('height', jQuery('html, body').height());

		jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
		jQuery('#message_box').show('slow');
		jQuery('#message_box').html( message );
	}
};

function close_message(level) {
	jQuery('#message_box').hide('fast');
	jQuery('#darkbg').hide();
	clearGame();
	loadLevel("level_" + level);
};

function loadLevel (levelname)
{
	$.getScript ("data/levels/" + levelname + ".js", function () {
		// this is the function that control most of the game logic 
		$.playground().registerCallback(function(){
			if(!gameOver){
				
				//$("#lifeHUD").html("life: "+$("#player")[0].player.replay);
				//Update the movement of the ship:
				if(!playerHit){
					$("#player")[0].player.update();
					if(jQuery.gameQuery.keyTracker[65]){ //this is left! (a)
						var nextpos = parseInt($("#player").css("left"))-5;
						if(nextpos > 0){
							$("#player").css("left", ""+nextpos+"px");
						}
					}
					if(jQuery.gameQuery.keyTracker[68]){ //this is right! (d)
						var nextpos = parseInt($("#player").css("left"))+5;
						if(nextpos < PLAYGROUND_WIDTH - 100){
							$("#player").css("left", ""+nextpos+"px");
						}
					}
				}
			}
		}, REFRESH_RATE);

		$.playground().startGame (function() {
			$("#welcomeScreen").fadeTo(1000, 0, function() {
				$(this).remove();
			});
		});
	});
	
	/*$.getJSON ("ajax.php", { load_level: levelname }, function (o) {
		try
		{
			if (o == null)
				//TODO Error Message!
				return;

			$(document).append ('<script type="text/javascript">' + o + '</script>');

			$.playground().startGame (function() {
				$("#welcomeScreen").fadeTo(1000, 0, function() {
					$(this).remove();
				});
			});
		}
		catch (ex)
		{
		}
	});*/
}

$(function() {
	// Initialize the game:
	$("#playground").playground ({ height: PLAYGROUND_HEIGHT, width: PLAYGROUND_WIDTH, keyTracker: true });

	// Player space ship annimations:
	playerAnimation["down"]		= new $.gameQuery.Animation ({ imageURL: "data/textures/models/player1/player.png" });
	playerAnimation["up"]		= new $.gameQuery.Animation ({ imageURL: "data/textures/models/player1/player_up.png" });

	//this is the HUD for the player life and shield
	//$("#overlay").append("<div id='shieldHUD'style='color: black; width: 100px; position: absolute; font-family: verdana, sans-serif;'></div><div id='lifeHUD'style='color: white; width: 100px; position: absolute; right: 0px; font-family: verdana, sans-serif;'></div>")
//	$("#overlay").append("<div id='pointHUD'style='color: black; z-index: 20; width: 100%; position: absolute; font-family: verdana, sans-serif;'></div>")
	$("#overlay").append("<div id='hub'></div>");

	// this sets the id of the loading bar:
	$().setLoadBar ("loadingBar", 400);

	//initialize the start button
	$("#startbutton").click (function(){
		loadLevel ("level_1")
	})

	//this is where the keybinding occurs
	$(document).keydown(function(e){
		if(!gameOver && !playerHit){
			switch(e.keyCode)
			{
				case 87: //this is up! (w)
					$("#playerBody").setAnimation(playerAnimation["up"]);
					isPlayerStaying = true;
					break;
			}
		}
	});

	//this is where the keybinding occurs
	$(document).keyup(function(e){
		if(!gameOver && !playerHit){
			switch(e.keyCode)
			{
				case 87: //this is up! (w)
					$("#playerBody").setAnimation(playerAnimation["down"]);
					isPlayerStaying = false;
					break;
			}
		}
	});
});